package main

import (
	"com.example.go/studygo/golang-server/common"
	"fmt"
	"net"
	"sync/atomic"
)

var count int64 = 0

func process(conn *net.TCPConn) {
	defer conn.Close()
	for {
		packet, err := common.ReadPacketFromTcp(conn)
		if err != nil {
			fmt.Println("decode msg failed, err:", err)
			return
		}
		if packet != nil {
			fmt.Printf("收到client发来的数据：%v\n", string(packet.Data))
            cTotal := atomic.AddInt64(&count, 1)
            fmt.Printf("共接受了%d条正常消息", cTotal)
			//break
		}
	}
}

func main() {
	fmt.Println("正在监听30000端口......")
	var tcpAddr *net.TCPAddr
	tcpAddr,_ = net.ResolveTCPAddr("tcp","127.0.0.1:30000")
	//打开一个tcp断点监听
	tcpListener,_ := net.ListenTCP("tcp",tcpAddr)
	defer tcpListener.Close()
	fmt.Println("Server ready to read ...")
	//循环接收客户端的连接，创建一个协程具体去处理连接
	for{
		tcpConn,err := tcpListener.AcceptTCP()
		if err!=nil {
			fmt.Println(err)
			continue
		}
		fmt.Println("A client connected :" +tcpConn.RemoteAddr().String())
		go process(tcpConn)
	}
}
